package com.hotec.PROJECT_NAME.modules.sys.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.hotec.PROJECT_NAME.component.enums.SmsEnum;
import com.hotec.PROJECT_NAME.utils.UtilsAccountValidator;
import com.hotec.PROJECT_NAME.utils.UtilsSms;
import com.hotec.PROJECT_NAME.utils.UtilsSpring;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public abstract class AbstractSmsService {
    private void valid(String mobile, String imgCode, String operateType){
        Assert.isTrue(UtilsAccountValidator.isMobile(mobile), "手机号码格式不正确");

        UtilsSms.validImgCode(mobile, imgCode, operateType);
    }

    private String createSmsCode (){
        return RandomUtil.randomString(4);
    }

    public void send(String mobile, String imgCode, SmsEnum type, String operateType){
        valid(mobile, imgCode, operateType);

        String smsCode = createSmsCode();

        postMsg(mobile, type, smsCode);

        handleSaveValidCode(mobile, smsCode, type);
    }

    abstract void postMsg (String mobile, SmsEnum type, String smsCode);

    private void handleSaveValidCode(String mobile, String validCode, SmsEnum type) {
        String key = type.name() + ":" + mobile;

        StringRedisTemplate redisTemplate = UtilsSpring.getBean(StringRedisTemplate.class);

        redisTemplate.delete(key);

        redisTemplate
                .opsForValue()
                .set(key, validCode, 60L, TimeUnit.SECONDS);
    }
}
